<template>
	<view class="pet-add-container">
		<view class="pet-header">
			<!-- 如果头像链接不存在，则使用默认头像 -->
			<image class="pet-avatar" :src="newPet.img || defaultAvatar" @click="chooseAvatar"></image>
		</view>
		<view class="pet-info">
			<view class="form-item">
				<view class="label">宠物名称:</view>
				<input type="text" v-model="newPet.name" placeholder="请输入宠物名称" class="input-border" />
			</view>
			<view class="form-item">
				<view class="label">性别:</view>
				<picker mode="selector" :range="genderOptions" @change="onGenderChange" v-model="genderIndex">
					<view class="picker">{{ newPet.gender || '请选择性别' }}</view>
				</picker>
			</view>
			<view class="form-item">
				<view class="label">年龄:</view>
				<input type="number" v-model="newPet.age" placeholder="请输入宠物年龄" class="input-border" />
				<text class="unit">岁</text>
			</view>
			<view class="form-item">
				<view class="label">体重:</view>
				<input type="text" v-model="newPet.petsize" placeholder="请输入宠物体重" class="input-border" />
				<text class="unit">kg</text>
			</view>
			<view class="form-item">
				<view class="label">宠物类型:</view>
				<picker mode="selector" :range="petTypeOptions" @change="onPetTypeChange" v-model="petTypeId">
					<view class="picker">{{ newPet.pettype_name || '请选择宠物类型' }}</view>
				</picker>
			</view>
			<view class="form-item">
				<view class="label">备注:</view>
				<textarea v-model="newPet.remark" placeholder="请输入备注" rows="3" class="input-border"></textarea>
			</view>
		</view>
		<view class="form-buttons">
			<button v-if="action === '编辑'" @click="submitPet">保存</button>
			<button v-if="action === '编辑'" @click="deletePet">删除</button>
			<button v-if="action === '新增'" @click="submitPet">完成</button>
			<button v-if="action === '新增'" @click="submitPet2">取消</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				newPet: {
					id: '',
					name: '',
					pettype_id: '',
					petsize: '',
					img: '', // 头像链接
					gender: '',
					age: '',
					remark: '',
					pettype_name: ''
				},
				action: '',
				genderOptions: ['雄性', '雌性', '中性'],
				petTypeOptions: ['请选择宠物类型'],
				petTypeNames: [], // 存储宠物类型名称
				petTypeIds: [], // 存储宠物类型ID
				genderIndex: 0,
				petTypeId: 0,
				defaultAvatar: 'https://petshop208.oss-cn-hangzhou.aliyuncs.com/23098751-ecb5-42d7-a25f-8fde20e2f107.png', // 默认头像链接
			};
		},
		onLoad(options) {
			this.fetchPetTypes();
			const eventChannel = this.getOpenerEventChannel();
			eventChannel.on('passData', (data) => {
				if (data.action === '编辑') {
					try {
						const petData = JSON.parse(data.pet);
						this.newPet = {
							id: petData.id,
							name: petData.name,
							pettype_id: petData.pettype_id,
							petsize: petData.petsize,
							img: petData.img || this.defaultAvatar, // 如果头像链接不存在，则使用默认头像
							gender: petData.gender,
							age: petData.age,
							remark: petData.remark,
							pettype_name: petData.pettype_name // 确保宠物类型名称也被设置
						};
						this.action = '编辑';
						this.genderIndex = this.genderOptions.indexOf(this.newPet.gender);
						const petTypeIndex = this.petTypeNames.indexOf(this.newPet.pettype_name);
						if (petTypeIndex !== -1) {
							this.petTypeId = petTypeIndex + 1; // +1 是因为petTypeOptions数组中第一个元素是'请选择宠物类型'
						}
					} catch (error) {
						console.error('Error parsing pet data:', error);
						uni.showToast({
							title: '数据解析失败',
							icon: 'none'
						});
					}
				} else if (data.action === '新增') {
					this.newPet = {
						id: '',
						name: '',
						pettype_id: '',
						petsize: '',
						img: this.defaultAvatar, // 默认头像
						gender: '',
						age: '',
						remark: '',
						pettype_name: ''
					};
					this.action = '新增';
					this.petTypeId = 0; // 默认选择“请选择宠物类型”
				}
			});
		},
		onUnload() {
			this.eventChannel && this.eventChannel.off('passData');
		},
		methods: {
			fetchPetTypes() {
				uni.request({
					url: 'http://localhost:8887/Pettype/findAll',
					method: 'GET',
					success: (res) => {
						if (res.data.code === 200) {
							this.petTypeNames = res.data.data.map(item => item.name);
							this.petTypeIds = res.data.data.map(item => item.id);
							this.petTypeOptions = [...new Set(this.petTypeNames)];
							this.petTypeOptions.unshift('请选择宠物类型'); // 添加默认选项
						}
					}
				});
			},
			onGenderChange(e) {
				this.newPet.gender = this.genderOptions[e.detail.value];
			},
			onPetTypeChange(e) {
				this.petTypeId = e.detail.value;
				this.newPet.pettype_name = this.petTypeOptions[this.petTypeId];
				if (this.petTypeId > 0) { // 确保选择了宠物类型
					this.newPet.pettype_id = this.petTypeIds[this.petTypeId - 1];
				}
			},
			chooseAvatar() {
				this.upload();
			},
			upload() {
				uni.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'],
					sourceType: ['album'],
					success: (res) => {
						const filePath = res.tempFilePaths[0];
						uni.uploadFile({
							url: 'http://localhost:8887/upload',
							filePath: filePath,
							name: 'file',
							success: (uploadRes) => {
								const data = JSON.parse(uploadRes.data);
								if (data.code === 200) {
									 if (this.action === '新增') {
									                  // 新增模式下，直接更新页面头像
									                  this.newPet.img = data.data; 
									                } else {
									                  this.updateImg(data.data);
									                }
								} else {
									uni.showToast({
										title: '上传失败',
										icon: 'none'
									});
								}
							},
							fail: () => {
								uni.showToast({
									title: '上传失败',
									icon: 'none'
								});
							}
						});
					}
				});
			},
			updateImg(imgUrl) {
				const token = uni.getStorageSync('Authorization');
				const url = 'http://localhost:8887/userpet/updateimg';
				const header = {
					'Authorization': token,
					'Content-Type': 'application/json',
				};
				const user = {
					id: this.newPet.id,
					img: imgUrl,
				};
				uni.request({
					url,
					method: 'POST',
					header,
					data: user,
					success: (res) => {
						if (res.data.code === 200) {
							this.newPet.img = res.data.data.img; // 更新本地宠物头像地址
							uni.showToast({
								title: '头像更新成功',
								icon: 'success'
							});
						} else {
							uni.showToast({
								title: '更新失败',
								icon: 'none'
							});
						}
					},
					fail: () => {
						uni.showToast({
							title: '请求失败',
							icon: 'none'
						});
					}
				});
			},
			submitPet2() {
				uni.navigateBack();
			},
			submitPet() {
				if (!this.newPet.name || !this.newPet.pettype_id || !this.newPet.petsize || !this.newPet.img || !this
					.newPet.gender || !this.newPet.age || !this.newPet.remark) {
					uni.showToast({
						title: '请填写所有字段',
						icon: 'none',
					});
					return;
				}
				const token = uni.getStorageSync('Authorization');
				const url = this.action === '编辑' ? 'http://localhost:8887/userpet/updateUserpetById' :
					'http://localhost:8887/userpet/addUserpet';
				const header = {
					'Authorization': token,
					'Content-Type': 'application/json',
				};
				uni.request({
					url,
					method: 'POST',
					header,
					data: this.newPet,
					success: (res) => {
						if (res.data.success) {
							uni.showToast({
								title: this.action === '编辑' ? '修改成功' : '新增成功',
								icon: 'success',
							});
							uni.reLaunch({
								url: '/pages/userpet/userpet',
							});
						} else {
							uni.showToast({
								title: '操作失败',
								icon: 'none',
							});
						}
					},
					fail: () => {
						uni.showToast({
							title: '请求失败',
							icon: 'none',
						});
					}
				});
			},
			deletePet() {
				const token = uni.getStorageSync('Authorization');
				const url = 'http://localhost:8887/userpet/deleteUserpetById?id=' + this.newPet.id;
				const header = {
					'Authorization': token,
				};
				uni.request({
					url,
					method: 'POST',
					header,
					success: (res) => {
						if (res.data.success) {
							uni.showToast({
								title: '删除成功',
								icon: 'success',
							});
							uni.reLaunch({
								url: '/pages/userpet/userpet',
							});
						} else {
							uni.showToast({
								title: '删除失败',
								icon: 'none',
							});
						}
					},
					fail: () => {
						uni.showToast({
							title: '请求失败',
							icon: 'none',
						});
					}
				});
			}
		},
	};
</script>

<style>
	.pet-add-container {
		padding: 10px;
	}

	.pet-header {
		display: flex;
		justify-content: center;
		margin-bottom: 20px;
	}

	.pet-avatar {
		width: 150px;
		height: 150px;
		border-radius: 50%;
	}

	.pet-info {
		margin-bottom: 20px;
	}

	.form-item {
		margin-bottom: 10px;
		display: flex;
		align-items: center;
	}

	.label {
		margin-bottom: 5px;
		display: block;
		width: 80px;
	}

	.input-border {
		border: 1px solid #ccc;
		padding: 10px;
		border-radius: 5px;
	}

	.picker {
		border: 1px solid #ccc;
		padding: 10px;
		border-radius: 5px;
		min-width: 100px;
		/* 限制下拉框宽度 */
	}

	.unit {
		margin-left: 10px;
		font-size: 14px;
		color: #888;
	}

	.form-buttons {
		display: flex;
		justify-content: space-between;
		margin-top: 20px;
	}
</style>